<template>
  <div class="auto-reply">
    <!-- 提示|创建 -->
    <div class="auto-reply-title">
      <p style="color: #999999; font-size: 14px">微信自动回复</p>
      <el-button
        style="background-color: #ff9f00; color: #fff; width: 105px; height: 32px"
        size="small"
        @click="showReplyDialog"
      >
        新增回复
      </el-button>
    </div>

    <!-- 展示自动回复 -->
    <el-table style="margin-top: 10px" :data="autoReply" stripe border>
      <!-- <el-table-column label="id" prop="id" width="100px"></el-table-column> -->
      <el-table-column label="匹配模式" prop="keyType" width="120px" :formatter="keyTypeFomatter"></el-table-column>
      <el-table-column label="关键词" prop="keyWord"></el-table-column>
      <el-table-column label="消息类型" prop="resourceType" :formatter="formateMsgType" width="80"></el-table-column>
      <el-table-column label="回复内容" prop="returnString">
        <template slot-scope="scope">
          <div
            :class="[
              {
                'chat-link': scope.row.resourceType === 6
              },
              {
                'chat-app': scope.row.resourceType === 13
              }
            ]"
            v-html="decodeChat(scope.row)"
          ></div>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180">
        <template slot-scope="scope">
          <span v-text="$options.filters.timeFilter(scope.row.createTime)"></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160px">
        <template slot-scope="scope">
          <el-button size="small" style="background-color: #fff; color: #999999" @click="showUpdateReply(scope.row)">
            编辑
          </el-button>
          <el-button
            size="small"
            style="background-color: #ff9f00; color: #ffffff"
            type="warning"
            @click="removeReply(scope)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加关键词回复 -->
    <el-dialog
      :title="reply2Updated ? '编辑关键词回复' : '新增关键词回复'"
      :close-on-click-modal="false"
      :show-close="false"
      append-to-body
      class="add-reply-dialog"
      :visible.sync="addReplyDialog"
    >
      <!-- 匹配方式 -->
      <div class="reply-item">
        <p class="reply-item-tip">匹配方式</p>
        <div style="margin-left: 10px">
          <el-radio v-model="keyType" size="small" label="0">精准匹配</el-radio>
          <el-radio v-model="keyType" size="small" label="1">模糊匹配</el-radio>
        </div>
      </div>
      <!-- 关键词 -->
      <div class="reply-item">
        <p class="reply-item-tip">关键词</p>
        <el-input
          v-model.trim="keyWord"
          style="margin-left: 10px"
          maxlength="20"
          size="mini"
          show-word-limit
          clearable
          placeholder="输入关键词"
        ></el-input>
      </div>

      <!-- content -->
      <div class="reply-content">
        <p class="reply-item-tip">回复内容</p>
        <div class="setting-reply-content">
          <!-- aside -->
          <ul class="add-reply-aside">
            <li
              v-for="(mt, index) in msgTypes"
              :key="index"
              :class="{ 'li-selected': msgType === mt.type }"
              @click="toggleType(mt.type)"
            >
              <i class="fa" :class="mt.icon" aria-hidden="true"></i>
              {{ mt.name }}
            </li>
          </ul>

          <div class="type-content" :class="{ 'link-form': msgType === 'Link' || msgType === 'WeApp' }">
            <!-- 文本 -->
            <el-input
              v-if="msgType === 'Text'"
              v-model.trim="returnString"
              type="textarea"
              placeholder="请输入内容"
              maxlength="500"
              show-word-limit
              resize="none"
            ></el-input>
            <!-- 图片 -->
            <template v-else-if="msgType === 'Picture'">
              <template v-if="!pictureUrl">
                <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiatupian.png" alt="" />
                <label style="cursor: pointer; padding: 5px" for="addPicture">
                  <i class="el-icon-plus"></i>
                  <span style="color: #576c95; font-size: 14px">添加图片</span>
                </label>
                <input
                  v-show="false"
                  id="addPicture"
                  ref="pictureInputRef"
                  type="file"
                  accept=".jpg, .png, .jpeg"
                  @change="chosePicture"
                />
              </template>
              <template v-else>
                <img style="max-width: 400px; max-height: 190px" :src="pictureUrl" alt="图片" />
                <div style="display: flex; align-items: center; height: 32px">
                  <p style="margin-right: 5px" v-text="pictureName"></p>
                  <i style="cursor: pointer" class="el-icon-delete" @click="deletePicture"></i>
                </div>
              </template>
            </template>
            <!-- 语音 -->
            <template v-else-if="msgType === 'Voice'">
              <template v-if="!voiceUrl">
                <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
                <label style="cursor: pointer; padding: 5px" for="addVoice">
                  <i class="el-icon-plus"></i>
                  <span style="color: #576c95; font-size: 14px">添加语音</span>
                </label>
                <input
                  v-show="false"
                  id="addVoice"
                  ref="voiceInputRef"
                  type="file"
                  accept=".mp3, .amr"
                  @change="choseVoice"
                />
              </template>
              <template v-else>
                <audio
                  style="max-width: 400px; max-height: 190px; margin-top: 60px"
                  :src="voicePlayUrl"
                  controls
                ></audio>
                <div style="display: flex; align-items: center; height: 32px">
                  <p style="margin-right: 5px" v-text="voiceName"></p>
                  <i style="cursor: pointer" class="el-icon-delete" @click="deleteVoice"></i>
                </div>
              </template>
            </template>
            <!-- 视频 -->
            <template v-else-if="msgType === 'Video'">
              <template v-if="!videoUrl">
                <img style="margin-top: 30px" src="../../../assets/images/circles/tianjiashipin.png" alt="" />
                <label style="cursor: pointer; padding: 5px" for="addPicture">
                  <i class="el-icon-plus"></i>
                  <span style="color: #576c95; font-size: 14px">添加视频</span>
                </label>
                <input
                  v-show="false"
                  id="addPicture"
                  ref="videoInputRef"
                  type="file"
                  accept=".mp4"
                  @change="choseVideo"
                />
              </template>
              <template v-else>
                <video style="max-width: 400px; max-height: 190px" :src="videoUrl" controls></video>
                <div style="display: flex; align-items: center; height: 32px">
                  <p style="margin-right: 5px" v-text="videoName"></p>
                  <i style="cursor: pointer" class="el-icon-delete" @click="deleteVideo"></i>
                </div>
              </template>
            </template>
            <!-- link -->
            <el-form
              v-else-if="msgType === 'Link'"
              ref="linkDialog"
              class="link-formt"
              :model="linkForm"
              :rules="linkRules"
              label-width="110px"
            >
              <el-form-item v-for="(link, index) in linkForm" :key="'link' + index" :label="index" :prop="index">
                <el-input v-model="linkForm[index]" :disabled="index === 'TypeStr'" clearable></el-input>
              </el-form-item>
            </el-form>
            <!-- weapp -->
            <el-form
              v-else-if="msgType === 'WeApp'"
              ref="weappDialog"
              :model="weapp"
              :rules="weappRules"
              label-width="110px"
            >
              <el-form-item v-for="(wa, index) in weapp" :key="'weapp' + index" :label="index" :prop="index">
                <el-input v-model="weapp[index]" clearable></el-input>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>

      <!-- footer -->
      <span slot="footer">
        <el-button size="small" @click="resetData">取 消</el-button>
        <el-button v-if="reply2Updated" type="primary" size="small" @click="updateReplyById">立即更新</el-button>
        <el-button v-else type="primary" size="small" @click="createReply">立即添加</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { fileUpload } from '@/utils/upload'
const imgError = require('@/assets/svg/conversation-image-error.svg')

import { getAutoReplyList, addReply, deleteReply, updateReply } from '@/api/httpApi'

export default {
  name: 'ToolsAutoReply',
  data() {
    return {
      autoReply: [],
      addReplyDialog: false, // 展示新增回复的dialog
      keyWord: '', // 关键词
      returnString: '', // 回复的内容
      reply2Updated: null, // 需要更新的回复,
      keyType: '0', // 匹配方式
      msgTypes: [
        {
          type: 'Text',
          icon: 'fa-file-text-o',
          name: '文本'
        },
        {
          type: 'Picture',
          icon: 'fa-file-image-o',
          name: '图片'
        },
        {
          type: 'Voice',
          icon: 'fa-microphone',
          name: '语音'
        },
        {
          type: 'Video',
          icon: 'fa-video-camera',
          name: '视频'
        },
        {
          type: 'Link',
          icon: 'fa-link',
          name: '链接'
        },
        {
          type: 'WeApp',
          icon: 'fa-product-hunt',
          name: '小程序'
        }
      ], // 消息类型
      msgType: 'Text', // 类型
      pictureUrl: '', // 要群发的图片url
      pictureName: '', // 要群发的图片名字
      voiceUrl: '', // 要群发的语音url
      voicePlayUrl: '', // 播放的语音
      voiceName: '', // 要群发的语音名字
      videoUrl: '', // 要群发的视频url
      videoName: '', // 要群发的视频名字
      weapp: {
        AppId: 'wxe99ba6e7fa3e8672',
        SourceName: 'gh_5b0c2f762fc0@app',
        Icon: 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5bBMPvk6Oohdlo4FpjGgLsTtcSYJKhibnoQWFphTVy7Bw/96',
        Source: '建业+',
        Title: '考拉之选 点断保鲜膜 食品级材质',
        Thumb:
          'http://gaia-projectc.oss-cn-hangzhou.aliyuncs.com/wxid_9988ti1oz81g22%2Fth_2fb4cbd7008c2e3cc33f6e49573c00cc.jpg',
        PagePath:
          'pages/index/index.html?_type=h5Link&h5url=https%3A%2F%2Fmall.yijiahn.com%2Fmall%2Fapp%2Fstatic%2Fgoods%2F3711147.html%3Fid%3D3711147&sharedUserId=2269485'
        // 'Des': '',
      }, // 小程序demo
      weappRules: {
        AppId: [{ required: true, message: '请输入AppId', trigger: 'blur' }],
        SourceName: [{ required: true, message: '请输入SourceName', trigger: 'blur' }],
        Icon: [{ required: true, message: '请输入Icon', trigger: 'blur' }],
        PagePath: [{ required: true, message: '请输入PagePath', trigger: 'blur' }],
        // Source: [
        //   { required: true, message: '请输入Source', trigger: 'blur' },
        // ],
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }]
      }, // 小程序表单验证
      linkForm: {
        Title: '“关闭领馆”落下帷幕! 外媒: 他们不再含泪抗议, 而是在大使馆前笑着合影',
        Thumb: 'http://www.jjldkj.com/files/phone/files/20200730/935FC7F27A771E914BD47DC261385309.jpg',
        Url: 'https://iflow.uc.cn/webview/news?app=meitullq-iflow&aid=17561738358438069514&cid=100&zzd_from=meitullq-iflow&uc_param_str=dndsfrvesvntnwpfgibicp&recoid=2043722754382504392&rd_type=reco&sp_gz=0&activity=1&activity2=1&dn=cf9807c357d1e8561c9aef3f75f05e71&enuid=AAPTn90AUlH8qpsGXMgpzgD%2BzWybOCOjkJX%2B2Ou9k8Lrzg%3D%3D&uc_iflow_biz=cmt%3A1&imei=bTkwAA3esoPsTi%2Ff%2FLrBSXG9zpdQ2YF7sw%3D%3D',
        Des: '震惊Des',
        TypeStr: '[链接]'
      }, // 链接demo
      linkRules: {
        Title: [{ required: true, message: '请输入Title', trigger: 'blur' }],
        Thumb: [{ required: true, message: '请输入Thumb', trigger: 'blur' }],
        Url: [{ required: true, message: '请输入Url', trigger: 'blur' }],
        Des: [{ required: true, message: '请输入Des', trigger: 'blur' }]
      } // 链接表单验证
    }
  },
  computed: {
    ...mapGetters({
      currentUser: 'currentUser',
      currentWeChatId: 'tools/currentWeChatId'
    })
  },
  watch: {
    currentWeChatId() {
      this.queryConfig()
    }
  },
  created() {
    // 读取线上的配置
    this.queryConfig()
  },
  methods: {
    showReplyDialog() {
      if (!this.currentWeChatId) {
        this.$alert('请选选中一个微信！', '提示', { type: 'warning' })
        return
      }
      this.addReplyDialog = true
    },
    // 切换类型
    toggleType(type) {
      this.msgType = type
    },
    // 选择图片
    chosePicture() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.pictureInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        // image/jpeg
        const isImage = file.type.indexOf('image') >= 0
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20

        if (!isImage) {
          this.$alert('图片格式不对！', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传图片大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.pictureName = file.name // 文件名
            this.pictureUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deletePicture() {
      this.pictureName = ''
      this.pictureUrl = ''
    },
    // 选择图片
    choseVideo() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.videoInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const isMP4 = file.type === 'video/mp4'
        const isLt2M = file.size > 0 && file.size / 1024 / 1024 < 20
        if (!isMP4) {
          this.$alert('上传视频只能是 MP4 格式!', '提示', { type: 'warning' })
          return
        }
        if (!isLt2M) {
          this.$alert('上传视频大小不能超过 20MB!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)
        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.videoName = file.name // 文件名
            this.videoUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除图片
    deleteVideo() {
      this.videoUrl = ''
      this.videoName = ''
    },
    // 选择语音
    choseVoice() {
      // 发送图片|视频|文件
      const fileObj = this.$refs.voiceInputRef.files // 文件对象
      // 如果有选中文件
      if (fileObj[0]) {
        const file = fileObj[0]
        const fileSize = file.size
        const fileName = file.name
        const fileType = fileName.replace(/.+\./, '').toLowerCase()
        // 文件大于10M不能发送
        if (fileSize > 104857600 || fileSize <= 0) {
          this.$alert('语音大小不能超过 10MB!', '提示', { type: 'warning' })
          return
        }
        // 验证文件类型
        if (['amr', 'mp3'].indexOf(fileType) < 0) {
          this.$alert('语音格式不对!', '提示', { type: 'warning' })
          return
        }
        // 验证通过
        const formdata = new FormData() // 上传
        formdata.append('myfile', file)

        // 如果选择的是mp3文件，文件上传到服务器，转为amr，返回amr的地址
        // 如果选择的是amr文件，直接上传到服务器，返回amr的地址
        if (fileType === 'mp3') {
          formdata.append('isMp3ToAmr', true)
        } else if (fileType === 'amr') {
          formdata.append('isAmrToMp3', false)
        }

        // 上传mp3 或者amr转为MP3
        const formDataMp3 = new FormData()
        formDataMp3.append('myfile', fileObj[0])
        if (fileType === 'mp3') {
          formDataMp3.append('isMp3ToAmr', false)
        } else if (fileType === 'amr') {
          formDataMp3.append('isAmrToMp3', true)
        }
        fileUpload(formDataMp3)
          .then((res) => {
            this.voicePlayUrl = res.data.url
          })
          .catch((err) => {
            this.$message.error(err)
          })

        const loading = this.$loading({
          lock: true,
          text: '文件上传中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        fileUpload(formdata)
          .then((res) => {
            this.voiceName = file.name // 文件名
            this.voiceUrl = res.data.url
            loading.close()
          })
          .catch((err) => {
            this.$alert(`${err}`, '文件上传失败', { type: 'error' })
            loading.close()
          })
      }
    },
    // 删除语音
    deleteVoice() {
      this.voiceUrl = ''
      this.voiceName = ''
    },

    // 查询自动回复的配置文件
    queryConfig() {
      if (!this.currentWeChatId) return
      getAutoReplyList(this.currentUser.SupplierId, this.currentWeChatId, '', '', '', 1, 1000)
        .then((res) => {
          if (res.code === 0) {
            this.autoReply = res.data.rows
          }
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 匹配模式
    keyTypeFomatter(row) {
      if (row.keyType === 1) {
        return '模糊包含匹配'
      } else if (row.keyType === 0) {
        return '精准完全匹配'
      } else {
        return '未知'
      }
    },
    formateMsgType(row) {
      if (row.resourceType === 1) {
        return '文本'
      } else if (row.resourceType === 2) {
        return '图片'
      } else if (row.resourceType === 3) {
        return '语音'
      } else if (row.resourceType === 4) {
        return '视频'
      } else if (row.resourceType === 6) {
        return '链接'
      } else if (row.resourceType === 13) {
        return '小程序'
      }
      return row.resourceType
    },
    // 提交表单
    createReply() {
      // 如果通过验证 提交表单
      if (!this.keyWord.trim()) {
        this.$alert('关键词不能为空！', '提示', { type: 'warning' })
        return
      }
      const resourceTypeMap = {
        Text: 1,
        Picture: 2,
        Voice: 3,
        Video: 4,
        Link: 6,
        WeApp: 13
      }
      let replyMsg = this.returnString
      if (this.msgType === 'Picture') {
        replyMsg = this.pictureUrl
      } else if (this.msgType === 'Voice') {
        replyMsg = this.voiceUrl
      } else if (this.msgType === 'Video') {
        replyMsg = this.videoUrl
      } else if (this.msgType === 'Link') {
        replyMsg = JSON.stringify(this.linkForm)
      } else if (this.msgType === 'WeApp') {
        replyMsg = JSON.stringify(this.weapp)
      }

      if (!replyMsg.trim()) {
        this.$alert('回复内容不能为空！', '提示', { type: 'warning' })
        return
      }
      // 添加
      addReply(
        this.currentUser.SupplierId,
        this.currentWeChatId,
        this.keyWord,
        this.keyType === '0' ? 0 : 1,
        resourceTypeMap[this.msgType],
        replyMsg
      )
        .then(() => {
          this.queryConfig()
          this.resetData()
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    },
    // 重置表单
    resetData() {
      this.addReplyDialog = false
      this.keyWord = ''
      this.returnString = ''
      this.reply2Updated = null
      this.keyType = '0'
      this.linkForm = {
        Title: '“关闭领馆”落下帷幕! 外媒: 他们不再含泪抗议, 而是在大使馆前笑着合影',
        Thumb: 'http://www.jjldkj.com/files/phone/files/20200730/935FC7F27A771E914BD47DC261385309.jpg',
        Url: 'https://iflow.uc.cn/webview/news?app=meitullq-iflow&aid=17561738358438069514&cid=100&zzd_from=meitullq-iflow&uc_param_str=dndsfrvesvntnwpfgibicp&recoid=2043722754382504392&rd_type=reco&sp_gz=0&activity=1&activity2=1&dn=cf9807c357d1e8561c9aef3f75f05e71&enuid=AAPTn90AUlH8qpsGXMgpzgD%2BzWybOCOjkJX%2B2Ou9k8Lrzg%3D%3D&uc_iflow_biz=cmt%3A1&imei=bTkwAA3esoPsTi%2Ff%2FLrBSXG9zpdQ2YF7sw%3D%3D',
        Des: '震惊Des',
        TypeStr: '[链接]'
      }
      this.weapp = {
        AppId: 'wxe99ba6e7fa3e8672',
        SourceName: 'gh_5b0c2f762fc0@app',
        Icon: 'http://wx.qlogo.cn/mmhead/Q3auHgzwzM5bBMPvk6Oohdlo4FpjGgLsTtcSYJKhibnoQWFphTVy7Bw/96',
        Source: '建业+',
        Title: '考拉之选 点断保鲜膜 食品级材质',
        Thumb:
          'http://gaia-projectc.oss-cn-hangzhou.aliyuncs.com/wxid_9988ti1oz81g22%2Fth_2fb4cbd7008c2e3cc33f6e49573c00cc.jpg',
        PagePath:
          'pages/index/index.html?_type=h5Link&h5url=https%3A%2F%2Fmall.yijiahn.com%2Fmall%2Fapp%2Fstatic%2Fgoods%2F3711147.html%3Fid%3D3711147&sharedUserId=2269485'
      }
    },
    // 删除自动回复
    removeReply(scope) {
      this.$confirm('确定删除 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 确认退出后，向服务端通知
          deleteReply(scope.row.id)
            .then(() => {
              this.queryConfig()
            })
            .catch((err) => {
              this.$message.error(err.message)
            })
        })
        .catch(() => {
          return false
        })
    },
    // 解析内容
    decodeChat(chat) {
      const content = chat.returnString
      const regJson = new RegExp(/^{.+}$/)
      let jContent = {}
      if (regJson.test(content)) {
        jContent = JSON.parse(content)
      }
      let thumb = ''
      let str = ''
      switch (chat.resourceType) {
        // 文本 1
        case 'Text':
        case 1:
          return content
        // 图片 2
        case 'Picture':
        case 2:
          return `<img class="chat-img" src="${content}"  alt="图片"/>`
        // 语音 3
        case 'Voice':
        case 3:
          if (content.endsWith('.amr')) {
            thumb = content.replace(/.amr$/, '.mp3')
          } else {
            thumb = content.replace(/.mp3:[0-9]+/, '.mp3')
          }
          return `<audio src="${thumb}" alt="语音" controls></audio>`
        // 视频 4
        case 'Video':
        case 4:
          return `<video class="video-box" src="${content}" type="video/mp4" alt="视频" controls></video>`
        // 链接消息 6
        case 'Link':
        case 6:
          str = `
                    <span class="link-title">${jContent.Title}</span>
                    <div class="link-content">
                      <span class="link-des">${jContent.Des}</span>
                      <img class="link-img" src="${jContent.Thumb}" alt="链接图片" />
                    </div>
                    <div class="link-type">${jContent.TypeStr}</div>
                    `
          return str

        // 小程序 13
        case 'WeApp':
        case 13: {
          let appIcon = imgError
          let appSource = '无效小程序'
          let appTitle = '无效小程序'
          let appThumb = ''
          let appTypeStr = '小程序'
          if (typeof content === 'string' && regJson.test(content)) {
            jContent = JSON.parse(content)
            appIcon = jContent.Icon && typeof jContent.Icon !== 'undefined' ? jContent.Icon : imgError
            appSource = jContent.Source
            appTitle = jContent.Title || jContent.Des
            appThumb = jContent.Thumb
            appTypeStr = jContent.TypeStr ? jContent.TypeStr : '小程序'
          }

          str = `
              <div class="app-des">
              <img class="app-icon" src="${appIcon}" alt="icon" />
              <span class="app-source ellipsis">${appSource}</span>
              </div>
              <div class="app-title ellipsis">${appTitle}</div>
              <img class="app-img" src="${appThumb}" />
              <div class="app-typestr">${appTypeStr}</div>
               `
          return str
          // return jContent
        }

        // 不支持的消息
        default:
          return `不支持的消息类型${chat.ContentType}`
      }
    },
    // 编辑回复内容
    showUpdateReply(row) {
      const msgTypeMap = {
        1: 'Text',
        2: 'Picture',
        3: 'Voice',
        4: 'Video',
        6: 'Link',
        13: 'WeApp'
      }
      this.reply2Updated = row
      this.keyWord = row.keyWord
      this.keyType = row.keyType === 1 ? '1' : '0'
      this.msgType = msgTypeMap[row.resourceType]
      if (row.resourceType === 1) {
        this.returnString = row.returnString
      } else if (row.resourceType === 2) {
        this.pictureUrl = row.returnString
      } else if (row.resourceType === 3) {
        this.voiceUrl = row.returnString
      } else if (row.resourceType === 4) {
        this.videoUrl = row.returnString
      } else if (row.resourceType === 6) {
        this.linkForm = JSON.parse(row.returnString)
      } else if (row.resourceType === 13) {
        this.weapp = JSON.parse(row.returnString)
      }
      this.addReplyDialog = true
    },
    // 更新关键词回复
    updateReplyById() {
      // 如果通过验证 提交表单
      if (!this.keyWord.trim()) {
        this.$alert('关键词不能为空！', '提示', { type: 'warning' })
        return
      }
      let replyMsg = this.returnString
      if (this.msgType === 'Picture') {
        replyMsg = this.pictureUrl
      } else if (this.msgType === 'Voice') {
        replyMsg = this.voiceUrl
      } else if (this.msgType === 'Video') {
        replyMsg = this.videoUrl
      }

      if (!replyMsg.trim()) {
        this.$alert('回复内容不能为空！', '提示', { type: 'warning' })
        return
      }
      updateReply(
        this.reply2Updated.id,
        this.currentUser.SupplierId,
        this.currentWeChatId,
        this.keyWord,
        this.keyType === '0' ? 0 : 1,
        this.reply2Updated.resourceType,
        replyMsg
      )
        .then(() => {
          this.queryConfig()
          this.resetData()
        })
        .catch((err) => {
          this.$message.error(err.message)
        })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .chat-link {
  flex-direction: column;
  width: 300px;
  max-width: 100%;
  cursor: pointer;
  .link-title {
    font-size: 14px;
    font-weight: 600;
  }
  .link-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    .link-des {
      flex: auto;
      color: #aaaaaa;
      font-size: 10px;
      margin-right: 5px;
      overflow: hidden;
      text-overflow: ellipsis;
      word-break: break-all;
      word-wrap: break-word;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
    }
    .link-img {
      max-width: 50px;
      max-height: 50px;
      min-height: 50px;
      min-width: 50px;
      border-radius: 5px;
    }
  }
  .link-type {
    color: #aaaaaa;
    margin-top: 5px;
    text-align: start;
    border-top: solid #e8eaec 1px;
  }
}
::v-deep .chat-app {
  width: 300px;
  max-width: 100%;
  cursor: pointer;
  display: flex;
  flex-direction: column;
  .app-des {
    display: flex;
    .app-icon {
      width: 20px;
      height: 20px;
    }
    .app-source {
      width: 100%;
      font-size: 12px;
      margin-left: 5px;
      color: gray;
    }
  }
  .app-title {
    width: 100%;
    height: 30px;
    font-size: 12px;
    font-weight: 600;
    line-height: 30px;
  }
  .app-img {
    align-self: center;
    max-width: 200px;
  }
  .app-typestr {
    height: 25px;
    margin-top: 5px;
    line-height: 25px;
    color: gray;
    text-align: start;
    border-top: solid #aaaaaa 1px;
  }
}
.auto-reply {
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  padding: 10px 20px;

  .auto-reply-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  // .el-form-my {
  //   position: relative;
  //   border-bottom: solid #ebeef5 1px;

  //   .el-form-item-my {
  //     width: 80%;
  //     margin-bottom: 0;
  //     margin: 20px 0;
  //   }

  //   .add-btn {
  //     position: absolute;
  //     right: 5%;
  //     top: 50%;
  //     transform: translate(-5%, -50%);
  //   }
  // }
}
</style>
